package com.zxw.hotel.api;

import com.github.pagehelper.PageInfo;
import com.zxw.hotel.common.Pageinfo;
import com.zxw.hotel.model.Admin;
import com.zxw.hotel.model.User;
import com.zxw.hotel.model.extend.AdminExtend;
import com.zxw.hotel.model.extend.UserExtend;
import com.zxw.hotel.service.UserService;
import org.jasypt.util.password.PasswordEncryptor;
import org.jasypt.util.password.StrongPasswordEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/user")
public class UserApi {
    private static final PasswordEncryptor encryptor = new StrongPasswordEncryptor();
    private UserService userService;

    @Autowired
    public UserApi(UserService userService) {
        this.userService = userService;
    }

    //查询 接受分页参数 userextends模型接受
    @GetMapping
    public Map<String, Object> getall(@RequestParam(defaultValue = "1") Integer pageNo,
                                      @RequestParam(defaultValue = "2147483647") Integer pageSize,
                                      UserExtend userExtend) {

        if (pageNo == null || pageNo < 1) {
            pageNo = 1;
        }
        if (pageSize == null || pageSize < 1) {
            pageSize = Integer.MAX_VALUE;
        }
        Pageinfo pageinfo = new Pageinfo(pageNo, pageSize);
        List<User> alluser = userService.getAll(pageinfo, userExtend);
        //通过分页插件获取分页信息
        PageInfo<User> pi = new PageInfo<>(alluser);
        Map<String, Object> map = Map.of("total", pi.getTotal(), "pageNo", pi.getPageNum(), "pageSize", pi.getPageSize());
        return Map.of("success", true, "data", alluser, "pi", map);

    }
    //新增
    @PostMapping
    public ResponseEntity<Map<String,Object>> add(@RequestBody User user) {
        if(user.getPassword()!=null){
            user.setPassword(encryptor.encryptPassword(user.getPassword()));
        }
        int add = userService.add(user);
        return ResponseEntity.ok().body(Map.of("success", add>0));
    }
    //修改
    @PutMapping
    public ResponseEntity<Map<String,Object>> update(@RequestBody User user) {
        if(user.getPassword()!=null){
            user.setPassword(encryptor.encryptPassword(user.getPassword()));
        }
        int update = userService.update(user);
        return ResponseEntity.ok().body(Map.of("success", update>0));
    }
    //删除
    @DeleteMapping
    public ResponseEntity<Map<String,Object>> delete(@RequestBody Integer[] ids) {
        int delete = userService.delete(ids);
        return ResponseEntity.ok().body(Map.of("success", delete>0));
    }
}
